<template>
  <div>

    <Spin v-if="loading" size="large" fix style="z-index:999;" />

    <section class="section" style="height:56px;margin:0;padding:1em;">
      <Row :gutter="8">
        <Col :xs="3" :sm="4" :md="4" :lg="3" :xl="2">
        <Button type="primary" ghost style="width:100%;" @click="toArticleList">
          <Icon type="ios-arrow-back" />
          <span v-if="screenWidth > 575">文章列表</span>
        </Button>
        </Col>
        <Col :xs="17" :sm="10" :md="12" :lg="12" :xl="10">
        <Input v-model="postForm.title" maxlength="100" show-word-limit placeholder="请输入100个字以内的文章标题" style="width:100%;" />
        </Col>
        <Col v-if="screenWidth > 575" :xs="6" :sm="6" :md="5" :lg="4" :xl="3">
        <Select v-model="postForm.code_style" style="width:100%" placeholder="选择编辑器样式">
          <!-- <Option v-for="(item, index) in codeStyleList" :value="item.label" :key="index">{{ item.label }}</Option> -->
        </Select>
        </Col>
        <Col :xs="4" :sm="4" :md="3" :lg="5" :xl="{ span: 3, offset: 6 }">
        <Button type="success" style="min-width:100%;" @click="onSubmit">保存</Button>
        </Col>
      </Row>
    </section>

    <div class="goods-editor" :style="{ height: editorHeight+'px' }">
      <!-- 工具栏容器 -->
      <div id="toolbar-container" />
      <!-- 编辑器容器 -->
      <div id="editor" />
    </div>

  </div>
</template>

<script>
import { storeContent, editContent, updateContent } from '@/api/blogContent/content'
import Setting from '@/settings'
import util from '@/libs/util'
import axios from 'axios'

// import CKEditor from '@ckeditor/ckeditor5-build-classic'
// import '@ckeditor/ckeditor5-build-classic/build/translations/zh-cn' // 中文包

// 自定义上传图片插件
class UploadAdapter {
  constructor(loader) {
    this.loader = loader
  }
  upload () {
    return new Promise((resolve, reject) => {
      console.log('dd', this.loader.file)

      var formdata = new FormData()
      formdata.append('file', this.loader.file)
      axios({
        method: 'post',
        url: `${Setting.apiBaseURL}/file/ckeditor`,
        data: formdata,
        headers: {
          'Accept': '*/*',
          'Authori-zation': 'Bearer ' + util.cookies.get('token')
        }
      }).then(response => {
        const res = response.data
        if (res.status === 200) {
          var resData
          resData.default = res.data.img_url
          resolve(resData)
        } else {
          reject(res.msg)
        }
      })
    })
  }
}

export default {
  name: 'ContentArticleNewRichText',
  components: {

  },
  data () {
    return {
      // 指定编辑的资源ID 0.新增 其他.指定的资源ID
      editId: 0,
      // 页面级加载等待
      loading: false,
      // 文章数据
      postForm: {
        title: '',
        content: '',
        content_html: '',
        code_style: 'monokai-sublime', // markdown样式
        editor_type: 'ckeditor',
        status: 5
      },

      // ######################################################################################################################

      // 编辑器高度
      editorHeight: document.body.clientHeight - 56,
      // 屏幕宽度
      screenWidth: document.body.clientWidth,

      // ######################################################################################################################

      // 编辑器实例
      editor: null

    }
  },
  watch: {
    screenWidth (val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val
        this.timer = true
        setTimeout(() => {
          this.timer = false
        }, 400)
      }
    }
  },
  mounted () {
    window.onresize = () => {
      return this.screenWidth = document.body.clientWidth
    }
    this.initCKEditor()
    this.editId = this.$route.params.id ? this.$route.params.id : 0
    if (this.editId) {
      this.getFormData()
    }
  },
  methods: {
    // 初始化编辑器
    initCKEditor () {
      CKEditor.create(document.querySelector('#editor'), {
        removePlugins: ['MediaEmbed'], // 除去视频按钮
        language: 'zh-cn', // 中文
        ckfinder: {
          'uploaded': true,
          'url': `${Setting.apiBaseURL}/file/ckeditor`
          // 后端处理上传逻辑返回json数据,包括uploaded(选项true/false)和url两个字段
        }
      }).then(editor => {
        const toolbarContainer = document.querySelector('#toolbar-container')
        toolbarContainer.appendChild(editor.ui.view.toolbar.element)
        // 加载了适配器
        editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
          return new UploadAdapter(loader)
        }
        this.editor = editor // 将编辑器保存起来，用来随时获取编辑器中的内容等，执行一些操作
      }).catch(error => {
        console.error(error)
      })
    },

    // ######################################################################################################################
    // # 写博客 MarkDown编辑器 保存和编辑 操作方法
    // ######################################################################################################################

    // 读取指定的资源用于编辑
    getFormData () {
      this.loading = true
      editContent(this.editId).then(async res => {
        if (res.status === 200) {
          this.postForm = res.data
          this.editor.setData(this.postForm.content)
          // this.editor.isReadOnly = true; //将编辑器设为只读
        } else {
          this.$Notice.error({ title: res.msg })
        }
        this.loading = false
      }).catch(res => {
        this.loading = false
        this.$Notice.error({ title: res.msg })
      })
    },
    // 提交表单
    onSubmit () {
      if (this.postForm.title == '') {
        this.$Message.warning('文章标题不能为空')
        return
      }
      this.postForm.content = this.editor.getData()
      if (this.editId) {
        this.handleUpdate(true)
      } else {
        this.handleStore()
      }
    },
    // 保存新建的资源
    handleStore () {
      this.loading = true
      storeContent(this.postForm).then(async res => {
        if (res.status === 200) {
          this.$Notice.success({ title: '保存成功' })
          this.$router.push({ path: '/new/richtext/' + res.data.akey })
        } else {
          this.$Message.error(res.msg)
        }
        this.loading = false
      }).catch(res => {
        this.$Message.error(res.msg)
        this.loading = false
      })
    },
    // 保存更新的资源
    handleUpdate (val = false) {
      if (this.editId) {
        updateContent(this.editId, this.postForm).then(async res => {
          if (res.status === 200) {
            val ? this.$Notice.success({ title: '保存成功' }) : this.$Message.success('保存成功')
          } else {
            this.$Message.error(res.msg)
          }
          this.loading = false
        }).catch(res => {
          this.$Message.error(res.msg)
          this.loading = false
        })
      }
    },

    // ######################################################################################################################
    // # 编辑器操作方法
    // ######################################################################################################################

    // 图片文件添加回调
    imgAdd (pos, $file) {
      var _this = this
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      formdata.append('file', $file)
      axios({
        method: 'post',
        url: `${Setting.apiBaseURL}/file/upload`,
        data: formdata,
        headers: {
          'Accept': '*/*',
          'Authori-zation': 'Bearer ' + util.cookies.get('token')
        }
      }).then(response => {
        const res = response.data
        if (res.status === 200) {
          this.$refs.mavonEditor.$img2Url(pos, res.data.img_url)
        } else {
          this.$Notice.error({ title: res.msg })
        }
      })
    },

    // 图片文件删除回调
    imgDel (val) {
      // let img_url = val[0]
      // this.$Message.info(JSON.stringify(img_url))
    },

    // 跳转到文章列表页
    toArticleList () {
      this.$router.push({ path: '/admin/article/list' })
    }

    // ######################################################################################################################
    // #
    // ######################################################################################################################

  }

}
</script>

<style scoped>
</style>
